<template>
	<view class="main bgColor-white" >
		<cu-custom :bgColor="TabCur==0?'bg-gradual-blue-light':'bg-gradual-orange-light'" :isBack="false" title="金华E人社">
		</cu-custom>
		<!-- 登录框 -->
		<view class="loginBox">
			<view class="logoImgBox">
				<text style="font-size: 150rpx;" class="iconfont icon-shebao" :class="TabCur==0?'text-blue-light':'text-orange-light'"></text>
			</view>
			<scroll-view scroll-x class="nav text-center">
				<view class="cu-item" style="font-size: 36rpx;" :class="index==TabCur?TabCur==0?'text-blue-light cur':'text-orange-light cur':'text-gray'" v-for="(item,index) in tabNav" :key="index" @tap="tabSelect"
				 :data-id="index">
					{{tabNav[index]}}
				</view>
			</scroll-view>
			<view v-if="loginType == 'username'" class="margin-top-sm">
				<zh-input type="text" v-model="userName"  maxlength="50" :placeholder="TabCur==0?'请输入身份证号/护照号/手机号码':'统一信用代码/管理员身份证/手机号'" :iconClass="['iconfont','icon-yonghu',TabCur==0?'text-blue-light':'text-orange-light']" ></zh-input>
			</view>
			<view v-if="loginType == 'cellphone'" class="margin-top-sm">
				<zh-input type="number" v-model="cellphone"  maxlength="11" :placeholder="TabCur==0?'请输入手机号码':'请输入管理员手机号码'" :iconClass="['iconfont','icon-shouji',TabCur==0?'text-blue-light':'text-orange-light']" ></zh-input>
			</view>
			<zh-picker
				v-if="TabCur==1"
				:iconClass="['iconfont','icon-danwei',TabCur==0?'text-blue-light':'text-orange-light']"
				:rightIconClass="TabCur==0?'text-blue-light':'text-orange-light'"
				pickerRef="org"
				mode="selector"
				:options="orgData"
				placeholder="请选择单位"
				:disabled="orgDisabled"
				themeColor="#f37b1d"
				@pickerChange="onOrgChange($event)"
				:defaultProps="{label:'orgName',value:'orgId'}"
				defaultType="orgId"
				ref="org"
			></zh-picker>
			<zh-input  v-if="loginType == 'username'"  v-model="userPassword" maxlength="16"  placeholder="请输入密码" :password="true" :iconClass="['iconfont','icon-mima',TabCur==0?'text-blue-light':'text-orange-light']" :rightIconClass="TabCur==0?'text-blue-light':'text-orange-light'"></zh-input>
			<view v-if="showImgCode" class="cu-form-group">
				<view class="title">
				<text class="iconfont icon-yanzhengma1"  :class="TabCur==0?'text-blue-light':'text-orange-light'"></text>
				</view>
				<input type="text" maxlength="4" name="" v-model="imgCode" placeholder="请输入图片验证码"/>
				<image :src="imgSrc" @click="initCode" mode="" class="img-captcha"></image>
			</view>
			<zh-input v-if="loginType == 'cellphone'" type="number" maxlength="4" v-model="shortMsgCode"  :iconClass="['iconfont','icon-yanzhengma',TabCur==0?'text-blue-light':'text-orange-light']" :rightButtonFlag="true" :rightButton="{disabled:!codeClick,text:codeBut,bg:TabCur==0?'bg-blue-light':'bg-orange-light'}" @right-button-click="getCode" placeholder="请输入手机验证码" ></zh-input>	
			
			<view class="flex flex-direction" style="padding-top: 10rpx;">
				<button class="cu-btn shadow margin-tb-sm lg" :class="TabCur==0?'bg-gradual-blue-light':'bg-gradual-orange-light'" @tap="loginUp">登<text style="width: 50rpx;"></text>录</button>
			</view>
			<view style="display: flex;justify-content:space-between;align-items:center;">
				<view  :class="TabCur==0?'text-blue-light':'text-orange-light'" @tap="loginTypeChange">
					{{loginTypeName}}
				</view>
				<view :class="TabCur==0?'text-blue-light':'text-orange-light'" style="display: flex;justify-content:flex-end;align-items:center;">
					<view  @tap="gotoForgetPassword">忘记密码</view>
					<text v-if="TabCur==0" style="padding: 0 8rpx 0 8rpx;">|</text>
					<view v-if="TabCur==0"  @tap="gotoRegistration">用户注册</view>
				</view>
			</view>
			<!--#ifdef MP-WEIXIN-->
			<view v-if="TabCur==0" style="display: flex;justify-content:center;align-items:center;padding-top: 40rpx; padding-bottom: 30rpx;">
				<button  class="cu-btn bg-white" open-type="getUserInfo" withCredentials="true" lang="zh_CN" @getuserinfo="weixinlogin">
				    <text style="font-size: 90rpx;" class="iconfont icon-weixin text-green"></text>
				</button>
			</view>
			<!-- #endif-->
			<!--#ifdef MP-ALIPAY -->
			<view style="display: flex;justify-content:center;align-items:center;padding-top: 20rpx;">
				<text style="font-size: 60rpx;" class="iconfont icon-zhifubao text-blue-light"></text>
			</view>
			<!-- #endif-->
			<!--#ifdef APP-PLUS || APP-PLUS-NVUE-->
			<view style="display: flex;justify-content:center;align-items:center;padding-top: 20rpx;">
				<text style="font-size: 60rpx;padding-right: 30rpx;" class="iconfont icon-weixin text-green" @click="weixinlogin"></text>	
				<text style="font-size: 60rpx;" class="iconfont icon-zhifubao text-blue-light"></text>
			</view>
			<!-- #endif-->
			<view class="bottomBox">
				登录注册即代表阅读并同意<text :class="TabCur==0?'text-blue-light':'text-orange-light'">服务协议</text>
			</view>
		</view>
	</view>
</template>

<script>
	import util from '@/common/util/util.js'
	import md5 from 'md5'
	import reqConfig from '@/common/config/reqConfig.js'
	import systemConfig from '@/common/config/systemConfig.js'
	import store from "@/store"
	import api from '@/api/system/login.js'
	export default {
		onReady() {
			if(!this.loginKey){
				this.loginKey = util.uuid()
			}
			/***
			if(store.state.hh_token){
				//校验token 有效则直接登录到主页
				const data = {}
				this.$http.post(api.getSessionInfo, data).then(res => {
					if(res.result){
						this.$u.vuex('hh_user', res.result)
						this.gotoHome();
					}
				}).catch(error => {
					
				})
			}***/
		},
		data() {
			return {
				loginCnt:0,
				isCanUse: uni.getStorageSync('isCanUse')||true,//默认为true 是否第一次授权登录
				windowHeight:this.$windowHeight,
				showPassword:true,
				showImgCode:false,
				imgSrc:"",
				TabCur: 0,
				tabNav: ['个人登录', '企业登录'],
				loginType: 'username',
				goBackFlag: false,
				codeBut:"获取验证码",
				codeTimer: "",//验证码定义一个定时器的变量
				codeClick:true,
				userName:"",
				cellphone:null,
				userPassword:"",
				shortMsgCode:"",
				orgId:"",
				loginKey: "",
				imgCode: "",
				loginTypeName:"手机快捷登录",
				userType:"20",
				orgDisabled:false,
				orgData:[{orgId:'1',orgName:'浙江xxx单位'},{orgId:'2',orgName:'金华xxx单位'}]
			}
		},
		onLoad(option) {
			if (this.$Route.query){
				let loginType=this.$Route.query.loginType;
				if(loginType){
					this.loginType = loginType
				}else {
					this.loginType = 'username'
				}
				let goBackFlag=this.$Route.query.goBackFlag;
				if(goBackFlag||goBackFlag=='true'){
					this.goBackFlag=true
				}else{
					this.goBackFlag=false
				}
			}else {
				this.loginType = 'username'
				this.goBackFlag=false
			}
			
		},
		methods: {
			initCode() {
				const url = reqConfig.baseUrl+"/sso/jycy/getImgCode?loginKey="+this.loginKey+"&time="+new Date().getTime()
				this.imgSrc=url
			},
			onOrgChange(e) {
				this.orgId = e.value;
			},
			loginCode() {
				this.loginType = "cellphone"
				this.loginTypeName="密码登录"
			},
			loginPhone() {
				this.loginType = "username"
				this.loginTypeName="手机快捷登录"
			},
			loginTypeChange(){
				if(this.loginType=='username'){
					this.loginCode()
				}else {
					this.loginPhone()
				}
			},
			tabSelect(e) {
				this.TabCur = e.currentTarget.dataset.id;
				if(this.TabCur==0){
					this.userType="20"
				}
				if(this.TabCur==1){
					this.userType="30"
				}
			},
			// 点击登录
			loginUp(){
				if(this.loginCnt>3){
					this.showImgCode = true
					this.initCode()
				}
				var _that = this
				if(_that.showImgCode){
					if(_that.imgCode == ""){
						uni.showToast({
							title: '请输入图片验证码',
							icon: 'none',
							duration:2000
						});
						return ;
					}
				}else {
					_that.imgCode = ""
				}
				if(_that.userName == "" && _that.loginType == 'username'){
					uni.showToast({
						title: '请输入用户名',
						icon: 'none',
						duration:2000
					});
					return ;
				}else if(_that.userPassword == "" && _that.loginType == 'username'){
					uni.showToast({
						title: '请输入密码',
						icon: 'none',
						duration:2000
					});
					return ;
				}else if(_that.cellphone == "" && _that.loginType == 'cellphone'){
					uni.showToast({
						title: '请输入手机号码',
						icon: 'none',
						duration:2000
					});
					return ;
				}else if(_that.shortMsgCode == "" && _that.loginType == 'cellphone'){
					uni.showToast({
						title: '请输入短信验证码',
						icon: 'none',
						duration:2000
					});
					return ;
				}else{
					const data = {};
					if ( _that.loginType == 'cellphone'){
						if (!this.$validate.isPhone(_that.cellphone)) {
						  uni.showToast({
						    icon: 'none',
						    title: '请输入正确的手机号',
							duration:2000
						  })
						  return
						}
						data.cellphone =_that.cellphone
						data.shortMsgCode =_that.shortMsgCode
					}else {
						data.userPassword = md5(_that.userPassword)
						data.userName = _that.userName
					}
					data.loginType = _that.loginType
					data.equipmentType = 'app'
					data.loginKey = this.loginKey
					data.userType= this.userType
					data.imgCode = _that.imgCode
					data.orgId = _that.orgId
					data.version = systemConfig.version
					data.systemCode = systemConfig.systemCode
					data.systemName = systemConfig.systemName
					//这里请求接口
					this.$http.post(api.login, data).then(res => {
						this.$u.vuex('hh_token', res.result.accessToken)
						this.$u.vuex('hh_openid', res.result.openId)
						this.$u.vuex('hh_userType', this.userType)
						this.loginCnt=0
						const sessionData={}
						this.$http.post(api.getSessionInfo, sessionData).then(res => {
							const sessionInfo=res.result
						    this.$u.vuex('hh_user', sessionInfo)
							if(this.goBackFlag){
								this.$Router.back(1)
							}else{
								this.gotoHome()
							}
						}).catch(error => {	
					})
					
						
					}).catch(error => {
						this.loginCnt= this.loginCnt+1
						if(error.code ){
							if(error.code == 40101){
								this.showImgCode = true
								this.initCode()
							}else if(error.code == 40102){
								this.isCanUse = true
								this.$u.vuex('hh_openid', '')
							}
							
						}
					})
				}
			},
			// 获取验证码
			getCode(){
				var _that = this
				// 倒计时
				if(_that.codeClick){
					if (!this.$validate.isPhone(_that.cellphone)) {
					  uni.showToast({
					    icon: 'none',
					    title: '请输入正确的手机号',
						duration:2000
					  })
					}else{
						// 发送短信
						const sendData = {};
						sendData.loginKey=this.loginKey;
						sendData.cellphone=this.cellphone;
						sendData.smsSendType= 'login';
						sendData.imgCode= this.imgCode;
						sendData.orgId= this.orgId;
						sendData.userType= this.userType;
						this.$http.post(api.loginSendMessage, sendData).then(res => {
							uni.showToast({
							  icon: 'none',
							  title: '短信发送成功',
							  duration:2000
							})
							_that.codeClick = false
							// 倒计时开始
							var daojishi = 60
							_that.codeTimer = setInterval(function(){
								_that.codeBut = "重新发送"+daojishi;
								daojishi--
								if(daojishi<=0){
									_that.codeBut = "重新发送"
									_that.codeClick = true
									clearInterval(_that.codeTimer);
								}
							},1000)
						}).catch(error => {
							
						})
						
					}
				}
			},
			// 微信登录
			weixinlogin(){
				console.log(store.state)
				let that = this
				uni.login({
					provider: 'weixin',
					success: function(loginRes) {
						let code = loginRes.code;
						// 校验openId是否绑定 通过则直接登录
						//这里请求接口
						uni.getUserInfo({
							provider: 'weixin',
							success: function(infoRes) {
								console.log(infoRes)
								that.gotoBindUser(code,infoRes);
							},
							fail(res) {
								that.gotoBindUser(code,null);	
							}
						})
					}
				})
				
			},
			gotoRegistration: function () {
				this.$Router.push({ name:'register', params: { userType: this.userType }})
			},
			gotoForgetPassword: function () {
				this.$Router.push({ name:'forgetPassword', params: { userType: this.userType }})
			},
			gotoBindUser: function (code,infoRes) {
				const data = {}
				data.code = code
				if(infoRes){
					data.encryptedData = infoRes.encryptedData
				}
				data.version = systemConfig.version
				data.systemCode = systemConfig.systemCode
				data.systemName = systemConfig.systemName
				data.userType=this.userType
				data.loginKey = this.loginKey
				data.orgId = this.orgId
				data.equipmentType = 'app'
				this.$http.post(api.winxinLogin, data).then(res => {
					this.$u.vuex('hh_token', res.result.accessToken)
					this.$u.vuex('hh_openid', res.result.openId)
					this.$u.vuex('hh_userType', this.userType)
					this.loginCnt=0
					setTimeout(() => {
					    const data={}
					    this.$http.post(api.getSessionInfo, data).then(res => {
					    	const sessionInfo=res.result
					    	this.$u.vuex('hh_user', sessionInfo)
							if(this.goBackFlag){
								this.$Router.back(1)
							}else{
								this.gotoHome()
							}
							
					    }).catch(error => {
					    	
					    })
					}, 100 );
					
				}).catch(error => {
					if(error.code){
						if(error.code == 40102){
							this.isCanUse = true
							if(error.result){
								console.log(error.result)
								this.$u.vuex('hh_openid', error.result.openId)
							}else{
								this.$u.vuex('hh_openid', '')
							}
							
							this.$Router.push({ name:'bindUser', params: { infoRes:infoRes,code:code,userType:this.userType }})
						}
						
					}
				})
			},
			gotoHome: function () {
				this.$Router.replaceAll({ name:'home'})
				//uni.switchTab({url:'pages/tabBar/home/home'})
			}
		},
		beforeDestroy() {
			if (this.codeTimer) {
			    clearInterval(this.codeTimer); // 在Vue实例销毁前，清除我们的定时器
			}
		}
	}
</script>

<style >
	.main {
		width: 100%;
		height: 100%;
	}
	
	.loginBox {
		width: 600rpx;
		margin: 0rpx auto;
		height: 600rpx;
	}
	.logoImgBox {
		text-align: center;
		height: 200rpx;
		margin: 0 auto;
		margin-bottom: 30rpx;
	}
	.bottomBox {
		display: flex;
		justify-content: center;
		padding-top: 60rpx;
		bottom: 30rpx;
		left: 0;
		right: 0;
		margin: auto;
		height: 30rpx;
		line-height: 30rpx;
		font-size: 28rpx;
	}
	.img-captcha{
		width: 200rpx;
		line-height: 70rpx;
		height: 70rpx;
		text-align: center;
		margin: 0;
	}
</style>
